package com.example.demo.service.aaaa.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.aaaa.Demo;
import com.example.demo.mapper.aaaa.DemoMapper;
import com.example.demo.service.aaaa.DemoService;
import com.example.demo.service.aaaa.MasterDemoService;
import com.example.demo.service.aaaa.SlaveDemoService;
import com.example.demo.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gjy
 * @ClassName DemoServiceImpl
 * @description
 * @date 2025/5/13 11:28
 */
@Service
public class DemoServiceImpl implements DemoService {
    private final DemoMapper demoMapper;
    private final MasterDemoService masterService;
    private final SlaveDemoService slaveService;
    private final RedisUtils redisUtils;

    @Autowired
    public DemoServiceImpl(DemoMapper demoMapper, MasterDemoService masterService, SlaveDemoService slaveService, RedisUtils redisUtils) {
        this.demoMapper = demoMapper;
        this.masterService = masterService;
        this.slaveService = slaveService;
        this.redisUtils = redisUtils;
    }

    @Override
    public String getDemoById(Long id) {
        Object string = redisUtils.getString("demo:" + id);
        if (string != null) {

            return JSON.toJSONString(string, JSONWriter.Feature.WriteNulls);
        }
        Demo demoById = demoMapper.getDemoById(id);
        redisUtils.setString("demo:" + id,  demoById,0);
        return JSON.toJSONString(demoById, JSONWriter.Feature.WriteNulls);
    }

    @Override
    public String searchDemos(Map<java.lang.String, Object> params) {
        List<Demo> demos = demoMapper.selectByCondition(params);
        return JSON.toJSONString(demos);
    }

    @Override
    public String getDemoById2(Long id) {
        Demo demoById = demoMapper.getDemoById2(id);
        return JSON.toJSONString(demoById, JSONWriter.Feature.WriteNulls);
    }

    @Override
    public String dataSynchronization() {
        Demo userByIdMaster = masterService.getDemoById(1L);
        Demo userByIdSlave = slaveService.getDemoById(1L);
        Map<String, Object> map = new HashMap<>();
        map.put("slave", userByIdSlave);
        map.put("master", userByIdMaster);
        return JSON.toJSONString(map);
    }

    @Override
    public String page() {
        Page<Demo> objectPage = new Page<>(1, 1);
        objectPage = demoMapper.selectPageList(objectPage);
        List<Demo> records = objectPage.getRecords();
        long total = objectPage.getTotal();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("records", records);
        jsonObject.put("total", total);
        return jsonObject.toString();
    }


}
